<template>
  <div class="login-container">
    <div class="logo">
      <img key="logo" :src="logoUrl" alt="">
      <span class="title">智慧测绘园</span>
    </div>
    <div class="login-content">
      <div class="title">欢迎使用</div>
      <div class="subtitle">智慧测绘园</div>

      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on"
        label-position="left">
        <!-- 账号密码错误 -->
        <el-form-item prop="username" v-if="isLogin">
          <div class="noLogin">
            <svg-icon style="margin-left: 8px;" slot="prefix" icon-class="Shape" class="el-input__icon input-icon" /><span
              class="noLogin-in">账号或密码错误</span>
          </div>
        </el-form-item>
        <!-- 账号 -->
        <el-form-item prop="username">
          <el-input ref="username" v-model="loginForm.username" clearable placeholder="账号" name="username" type="text"
            tabindex="1" autocomplete="on" size="medium">
            <!-- <svg-icon slot="prefix" icon-class="account" class="el-input__icon input-icon" /> -->
          </el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password">
            <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
              placeholder="密码" name="password" tabindex="2" autocomplete="on" @keyup.native="checkCapslock"
              @blur="capsTooltip = false" @keyup.enter.native="handleLogin" @input="onPwdInput($event,'password')">
              <!-- <svg-icon icon-class="password" />
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" /> -->

            </el-input>
            <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
          </el-form-item>
        </el-tooltip>
        <!-- 验证码 -->
        <!-- <el-form-item prop="code" v-if="captchaOnOff">
          <el-input ref="code" style="width: calc(100% - 120px)" maxlength="4" v-model="loginForm.code" placeholder="验证码" name="code"
            type="text" tabindex="3" size="medium" @keyup.enter.native="handleLogin">
            <svg-icon slot="prefix" icon-class="validCode" />
          </el-input>

          <div class="login-code" >
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item> -->

        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;height:46px"
          @click.native.prevent="handleLogin">登录</el-button>
      </el-form>

      <!-- <div style="font-size: 20px; font-weight: 700; color: red; text-align: center;">
        {{ water }}
      </div> -->
    </div>
    <!-- <el-dialog title="Or connect with" :visible.sync="showDialog">
      Can not be simulated on local, so please combine you own business simulation! ! !
      <br>
      <br>
      <br>
      <social-sign />
    </el-dialog> -->
    <!-- <div class="box">
      <span @click="navTo" class="box-sp">网站备案号：鲁ICP备2021039051号-1</span>
    </div> -->
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import {getCodeImg} from '@/api/login'
import Cookies from "js-cookie";
import { encrypt, decrypt, } from '@/utils/jsencrypt'
import {toCDB} from "@/utils/witvsp";
import md5 from 'js-md5'
import {mobileDevice} from '@/utils/index.js'
import * as dd from 'dingtalk-jsapi'; // 此方式为整体加载，也可按需进行加载

export default {
  name: 'Login',
  components: {},
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      water: undefined,
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        // code: ""
      },
      codeUrl: "",
      isLogin: false,
      showLogin: false,
      // 验证码开关
      captchaOnOff: true,
      loginRules: {
        // username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        // password: [{ required: true, trigger: 'blur', validator: validatePassword }]
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        // code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      logoUrl: require("@/assets/images/logo.png"),

    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect && route.query.redirect;
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
    this.getCookie();
    // this.getCode();
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {

    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.enable === undefined ? true : res.enable;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.code;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
      console.log(this.loginForm)
    },
    onPwdInput(value, keyName){
      if (/[^\x00-\xff]/g.test(value)) {
        return this.loginForm[keyName] = toCDB(value)
      } else {
        return value
      }
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      // this.$router.push({ path: '/' });
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          let value={...this.loginForm}
          value.password=md5(value.password)
          this.$store.dispatch('Login', value)
            .then(() => {
              // this.$router.push({ path: '/' });
              this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
              this.loading = false
            })
            .catch((res) => {
              console.log(res)
              this.loading = false;
              // if (this.captchaOnOff) {
              //   this.getCode();
              // }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    navTo() {
      window.open('https://beian.miit.gov.cn/')
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
}
</script>

<style lang="scss" scoped>
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;


/* reset element-ui css */
.login-container {
  background-image: url('../assets/images/login-bg.png');
  background-size: 100% 100%;
  height: 100%;
  // width: 100%;
  padding-top: 60px;
  padding-left: 60px;

  .logo {
    img {
      width: 174px;
      height: 54px;
      float: left;
    }

    .title {
      // margin-top: 15px;
      float: left;
      width: 325px;
      height: 50px;
      opacity: 0.65;
      font-family: PingFangSC-Medium;
      font-weight: 500;
      font-size: 32px;
      color: #000000;
      // letter-spacing: 2.67px;
    }
  }

  .adver {
    width: 40.7%;
    height: 70.2%;
    margin-left: 6.7%;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .login-content {
    width: 410px;
    height: 500px;
    background: #FFFFFF;
    box-shadow: 0 0 30px 0 rgba(0, 0, 0, 0.10);
    border-radius: 4px;
    position: absolute;
    top: 20.82%;
    right: 11.4%;
    padding: 60px 40px 0px 40px;

    .title {
      width: 167px;
      height: 42px;
      font-family: PingFangSC-Medium;
      font-weight: 500;
      font-size: 28px;
      color: #333333;
      // letter-spacing: 3.33px;
    }

    .subtitle {
      width: 232px;
      height: 22px;
      // opacity: 0.65;
      font-family: PingFangSC-Medium;
      font-weight: 500;
      font-size: 18px;
      color: #333333;
      // letter-spacing: 1.78px;
      margin-top: 14px;
    }

    .login-form {
      position: relative;
      margin: 0 auto;
      overflow: hidden;
      margin-top: 33px;
      width: 330px;

      ::v-deep .el-input--medium .el-input__inner{
        height: 46px !important;
        line-height: 46px !important;
      }
      ::v-deep .el-form-item--medium .el-form-item__content{
        line-height: 46px !important;
      }

      // ::v-deep(.el-form-item) {
        // .el-form-item__content {
        //   line-height: 46px;
        //   .el-input--medium .el-input__inner {
        //     // width: 320px !important;
        //     height: 46px !important;
        //     line-height: 46px !important;
        //     background: #a71212;
        //     border-radius: 2px;
        //   }
        //   .el-input--prefix .el-input__inner{
        //     border-radius: 2px;
        //     height: 46px;
        //   }

        // }

        // .code {
        //   .el-form-item__content {
        //     .el-input--medium .el-input__inner {
        //       width: 200px !important;
        //       height: 40px !important;
        //     }
        //   }
        // }
      // }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      // top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 1000px) {
      .thirdparty-button {
        display: none;
      }
    }
  }

  .login-code {
    // width: 110px;
    height: 36px;
    float: right;

    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }

  .login-code-img {
    height: 36px;
  }

  .box {
    position: absolute;
    bottom: 5px;
    left: 0;
    width: 100%;
    text-align: center;
    background: transparent;

    .box-sp {
      width: 242px;
      height: 20px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.25);
      letter-spacing: 0;
    }
  }

  .noLogin {
    background: #FFF1F0;
    border: 1px solid #FFCCC7;
    border-radius: 2px;
    width: 398px;
    height: 36px;
    line-height: 36px;
  }

  .noLogin-in {
    width: 98px;
    height: 22px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.65);
    letter-spacing: 0;
    line-height: 22px;
    margin-left: 8px
  }

  ;
}
</style>

